package cn.edu.laud.sany.datatest;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class RandomKeys {
	
	public static  class Iterm {
		public String key;
		public String cf;
		
		public Iterm(String k, String c) {
			key = k;
			cf = c;
		}
	}
	
	public static List<Iterm> getRandomKeys(String sfolder, String sCount) {
		int iCount = Integer.parseInt(sCount);		
		File folder = new File(sfolder);
		File[] allfiles =null;
		if(folder.isDirectory())
			 allfiles = folder.listFiles();
		else
			allfiles=new File[]{folder};
			
		ArrayList<File> files = new ArrayList<File>();
		for (File f: allfiles) {
			if (!f.isDirectory()) {
				files.add(f);
			}
		}
		int fCount = files.size();
		
		Random random = new Random(System.currentTimeMillis());
		List<Iterm> iterms = new ArrayList<Iterm>();
		List<String> keys = new ArrayList<String>();
		while (iterms.size() < iCount) {
			try {
				File file = files.get(random.nextInt(fCount));
				keys.clear();
				BufferedReader fReader = new BufferedReader(new FileReader(file));
				String key = fReader.readLine();
				while (key != null && key.length() > 0) {
					keys.add(key);
					key = fReader.readLine();
				}
				String selectedKey = keys.get(random.nextInt(keys.size()));
				//check if there is same key
				boolean hasSame = false;
				for (Iterm iterm: iterms) {
					if (iterm.key.equals(selectedKey)) {
						hasSame = true;
						break;
					}
				}
				if (!hasSame) {					
					iterms.add(new Iterm(selectedKey, file.getName()));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}					
		}
		return iterms;
	}

	public static void main(String[] args) {

		if(args.length < 2) {
			System.err.println("need arguments");
		}
		RandomKeys randomKeys = new RandomKeys();
		List<Iterm> iterms = randomKeys.getRandomKeys(args[0], args[1]);
		for (Iterm iterm: iterms) {
			//System.out.println(iterm.key + " " + iterm.cf);
		}
		
	}

}
